package com.yangluyao.test.blockingqueue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author YLY
 * @ClassName ProdConsumer_TraditionDemo 传统版生产者消费者模式
 * @Date 2020/5/11
 * @Version 1.0.2
 */

class ShareData {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //1、判断
            while (number != 0) {
                condition.await();
            }
            //2、操作
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3、通知唤醒
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            //1、判断
            while (number == 0) {
                condition.await();
            }
            //2、操作
            number--;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3、通知唤醒
            condition.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 线程通信之生产者消费者传统版
 */
public class ProdConsumer_TraditionDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(()->{
            for (int i = 1; i <=5 ; i++) {
                try {

                    shareData.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 1; i <=5 ; i++) {
                try {
                    shareData.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();
    }
}
